package pl.edu.agh.io.gpstracker.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.edu.agh.io.gpstracker.client.dto.TrackDto;
import pl.edu.agh.io.gpstracker.client.dto.TracksequanceDto;
import pl.edu.agh.io.gpstracker.dao.NodeDao;
import pl.edu.agh.io.gpstracker.dao.TrackDao;
import pl.edu.agh.io.gpstracker.dao.TrackSequenceDao;
import pl.edu.agh.io.gpstracker.model.Node;
import pl.edu.agh.io.gpstracker.model.Track;
import pl.edu.agh.io.gpstracker.model.Tracksequence;

@Service(value="tackService")
@Transactional
public class TrackServiceImpl extends GenericService<Track, TrackDto> implements
		TrackService {

	@Autowired
	private TrackDao trackDao;

	@Autowired
	private TrackSequenceDao trackSequenceDao;
	
	@Autowired
	private NodeDao nodeDao;

	public TrackServiceImpl() {
		super(Track.class, TrackDto.class);
	}

	@Transactional
	public void addWaySequenceToTrack(TracksequanceDto way)
			throws DataAccessException {	
		nodeDao.saveOrUpdate(mapper.map(way.getNode(), Node.class));
		trackSequenceDao.saveOrUpdate(mapper.map(way, Tracksequence.class));
	}

	@Transactional(readOnly = true)
	public List<TrackDto> findAllByUser(Integer userId)
			throws DataAccessException {
		return mapEntityList(trackDao.findTrackByUser(userId));
	}

	@Transactional
	public void saveOrUpdateTrack(TrackDto trackDto) throws DataAccessException {
		trackDao.saveOrUpdate(mapDto(trackDto));
	}

	public TracksequanceDto getLastPositionForTrack(Long trackId)
			throws DataAccessException {
		return mapper.map(trackSequenceDao.getLastPosition(trackId),
				TracksequanceDto.class);
	}
}
